import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/user.dart';

class UserController extends ChangeNotifier {
  User _user = User(
    id: '1',
    name: 'Guest',
    coins: 0,
    unlockedCharacters: [],
    chatHistory: {},
  );

  User get user => _user;

  Future<void> initializeUser() async {
    final prefs = await SharedPreferences.getInstance();
    final userJson = prefs.getString('user');
    if (userJson != null) {
      _user = User.fromJson(Map<String, dynamic>.from(
        const JsonDecoder().convert(userJson),
      ));
      notifyListeners();
    } else {
      _user = User(
        id: 'default_user',
        name: 'user',
        coins: 100,
        unlockedCharacters: ['default_character'],
        chatHistory: {},
      );
      await saveUser();
    }
  }

  Future<void> saveUser() async {
    if (_user != null) {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('user', const JsonEncoder().convert(_user!.toJson()));
    }
  }

  void updateCoins(int newCoins) {
    _user = _user.copyWith(coins: newCoins);
    notifyListeners();
  }

  void addCoins(int amount) {
    _user = _user.copyWith(coins: _user.coins + amount);
    notifyListeners();
  }

  void deductCoins(int amount) {
    if (_user.coins >= amount) {
      _user = _user.copyWith(coins: _user.coins - amount);
      notifyListeners();
    }
  }

  void unlockCharacter(String characterId) {
    if (!_user.unlockedCharacters.contains(characterId)) {
      final updatedCharacters = List<String>.from(_user.unlockedCharacters)
        ..add(characterId);
      _user = _user.copyWith(unlockedCharacters: updatedCharacters);
      notifyListeners();
    }
  }

  void addChatMessage(String characterId, String message) {
    final updatedHistory = Map<String, List<String>>.from(_user.chatHistory);
    if (!updatedHistory.containsKey(characterId)) {
      updatedHistory[characterId] = [];
    }
    updatedHistory[characterId]!.add(message);
    _user = _user.copyWith(chatHistory: updatedHistory);
    notifyListeners();
  }
} 